package com.example.jimuyutabletcontrol.main;

import android.animation.Animator;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.animation.AccelerateInterpolator;
import android.widget.LinearLayout;

import com.example.jimuyutabletcontrol.R;
import com.example.jimuyutabletcontrol.fragment.SplitFragment;
import com.example.jimuyutabletcontrol.network.HFTCPBuild;
import com.example.jimuyutabletcontrol.sidemenu.interfaces.Resourceble;
import com.example.jimuyutabletcontrol.sidemenu.interfaces.ScreenShotable;
import com.example.jimuyutabletcontrol.sidemenu.model.SlideMenuItem;
import com.example.jimuyutabletcontrol.sidemenu.util.ViewAnimator;
import com.example.jimuyutabletcontrol.utils.Constants;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;

public class SplitActivity extends AppCompatActivity implements ViewAnimator.ViewAnimatorListener {
    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle drawerToggle;
    private List<SlideMenuItem> list = new ArrayList<>();
    private ViewAnimator viewAnimator;
    private LinearLayout linearLayout;
    public Boolean mappingRecord;
    private String part;

    private static SplitActivity self;
    public static SplitActivity getInstance() {
        return self;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.maininterface_activity);

        this.self = this;

        part = getIntent().getStringExtra("part");

        useDomReadXml(this.getApplicationContext());

        SplitFragment splitFragment = SplitFragment.newInstance(SplitFragment.CONTROLACTIVITY);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_frame, splitFragment)
                .commit();
        drawerLayout = findViewById(R.id.drawer_layout);
        drawerLayout.setScrimColor(Color.GRAY);
        linearLayout = findViewById(R.id.left_drawer);
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.closeDrawers();
            }
        });

        setActionBar();
        createMenuList();
        viewAnimator = new ViewAnimator<>(this, list, null, drawerLayout, this);

        new Thread(new Runnable() {
            @Override
            public void run() {
                HFTCPBuild.INSTANCE.getTcpServer().tcpWorker();
            }
        }).start();

    }

    private void createMenuList() {

        switch (part) {
            case "0" :
                SlideMenuItem menuItem0 = new SlideMenuItem(SplitFragment.CLOSE, R.drawable.maininterface_icn_close);
                list.add(menuItem0);
                SlideMenuItem menuItem1 = new SlideMenuItem(SplitFragment.CONTROLACTIVITY, R.drawable.splitinterface_handcontrol);
                list.add(menuItem1);
                SlideMenuItem menuItem2 = new SlideMenuItem(SplitFragment.ONLINEAUVACTVITY, R.drawable.splitinterface_quiryinformation);
                list.add(menuItem2);
                SlideMenuItem menuItem3 = new SlideMenuItem(SplitFragment.SAILTASKACTIVITY, R.drawable.splitinterface_settask);
                list.add(menuItem3);
                break;
        }

    }

    private void setActionBar() {

        //Toolbar toolbar = findViewById(R.id.toolbar);
        //setSupportActionBar(toolbar);
        //getSupportActionBar().setHomeButtonEnabled(true);
        //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        drawerToggle = new ActionBarDrawerToggle(
                this,
                drawerLayout,
                null,
                R.string.drawer_open,
                R.string.drawer_close)
        {

            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                linearLayout.removeAllViews();
                linearLayout.invalidate();
            }

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                super.onDrawerSlide(drawerView, slideOffset);
                if (slideOffset > 0.6 && linearLayout.getChildCount() == 0)
                    viewAnimator.showMenuContent();
            }
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }
        };
        drawerLayout.addDrawerListener(drawerToggle);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mappingRecord = false;
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        //drawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //drawerToggle.onConfigurationChanged(newConfig);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        //if (drawerToggle.onOptionsItemSelected(item)) {
        //    return true;
        //}

        switch (item.getItemId()) {
            case R.id.action_settings:
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private ScreenShotable replaceFragment(ScreenShotable screenShotable, int topPosition, String res) {

        View view = findViewById(R.id.content_frame);
        int finalRadius = Math.max(view.getWidth(), view.getHeight());
        Animator animator = ViewAnimationUtils.createCircularReveal(view, 0, topPosition, 0, finalRadius);
        animator.setInterpolator(new AccelerateInterpolator());
        animator.setDuration(ViewAnimator.CIRCULAR_REVEAL_ANIMATION_DURATION);

        findViewById(R.id.content_overlay).setBackground(new BitmapDrawable(getResources(), screenShotable.getBitmap()));
        animator.start();

        SplitFragment splitFragment = SplitFragment.newInstance(res);
        getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, splitFragment).commit();
        return splitFragment;
    }

    @Override
    public ScreenShotable onSwitch(Resourceble slideMenuItem, ScreenShotable screenShotable, int position) {
        switch (slideMenuItem.getName()) {
            case SplitFragment.CLOSE:
                return screenShotable;
            default:
                return replaceFragment(screenShotable, position, slideMenuItem.getName());
        }
    }

    @Override
    public void disableHomeButton() {
        //getSupportActionBar().setHomeButtonEnabled(false);

    }

    @Override
    public void enableHomeButton() {
        //getSupportActionBar().setHomeButtonEnabled(true);
        //drawerLayout.closeDrawers();

    }

    @Override
    public void addViewToContainer(View view) {
        linearLayout.addView(view);
    }

    public static void useDomReadXml(Context context){
        Document doc = null;
        try {
            InputStream resource = context.getResources().openRawResource(R.raw.properties);//TODO raw文件的建立
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            doc = builder.parse(resource);
        } catch (Exception e) {
            System.err.println("读取该xml文件失败");
            e.printStackTrace();
        }

        if (doc != null) {
            NodeList list = doc.getElementsByTagName("menu");
            for (int i = 0; i < list.getLength(); i ++) {
                String name = doc.getElementsByTagName("name").item(i).getFirstChild().getNodeValue();
                String[] colors = doc.getElementsByTagName("color").item(i).getFirstChild().getNodeValue().split(",");
                String[] titles = doc.getElementsByTagName("title").item(i).getFirstChild().getNodeValue().split(",");
                String[] activitys = doc.getElementsByTagName("activity").item(i).getFirstChild().getNodeValue().split(",");

                ArrayList<String> tmpColor = new ArrayList<>();
                ArrayList<String> tmpTitle = new ArrayList<>();
                ArrayList<String> tmpActivity = new ArrayList<>();

                for (String color : colors) {
                    tmpColor.add(color);
                }

                for (String title : titles) {
                    tmpTitle.add(title);
                }

                for (String activity: activitys) {
                    tmpActivity.add(activity);
                }

                Constants.color.put(name, tmpColor);
                Constants.title.put(name, tmpTitle);
                Constants.activity.put(name, tmpActivity);
            }
        }
    }
}
